package com.yifeng.repo.micro.service.server.engine.request;

import com.yifeng.repo.base.utils.common.BaseUtil;
import com.yifeng.repo.micro.service.server.engine.dal.TransactionTargetManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.boot.CommandLineRunner;

/**
 * Created by daibing on 2023/3/27.
 */
@Slf4j
public class AppLifeCycleListener implements CommandLineRunner, DisposableBean {
    private static final String YFCLOUD_REPO_VERSION = "1.5.6-SNAPSHOT";
    private final String applicationName;
    private final boolean isPrintLog4ForceTransaction;

    public AppLifeCycleListener(String applicationName, boolean isPrintLog4ForceTransaction) {
        this.applicationName = applicationName;
        this.isPrintLog4ForceTransaction = isPrintLog4ForceTransaction;
    }

    /**
     * 备注：
     * 1、SpringBoot提供CommandLineRunner和ApplicationRunner，Spring提供InitializingBean，jdk提供@PostConstruct
     * 2、执行顺序：static > @PostConstruct > InitializingBean > ApplicationRunner > CommandLineRunner
     * 3、同类顺序：可以使用@Order注解或实现Ordered接口
     * 4、依赖注入：Constructor > @Autowired > @PostConstruct
     */
    @Override
    public void run(String... args) throws Exception {
        log.info("Startup success: appId={}, OwnerId={}, OwnerName={}, yfcloudRepoVersion={}, writeMethodCount={}, extraWriteMethodCount={}, readMethodCount={}",
                applicationName, BaseUtil.OWNER_ID, BaseUtil.OWNER_NAME, YFCLOUD_REPO_VERSION,
                TransactionTargetManager.writeMethodCount(), TransactionTargetManager.extraWriteMethodCount(), TransactionTargetManager.readMethodCount());
        if (isPrintLog4ForceTransaction) {
            TransactionTargetManager.listWriteMethod().forEach((k, v) -> log.info("write transaction: entry={}, target={}", v, k));
            TransactionTargetManager.listExtraWriteMethod().forEach((k, v) -> log.info("extra write transaction: entry={}, target={}", v, k));
            TransactionTargetManager.listReadMethod().forEach((k, v) -> log.info("read transaction: entry={}, target={}", v, k));
        }
    }

    @Override
    public void destroy() throws Exception {
        log.info("Shutdown yfcloud micro service server {}, Good bye: OWNER_ID={}, OWNER_ID={}, yfcloudRepoVersion={}",
                applicationName, BaseUtil.OWNER_ID, BaseUtil.OWNER_NAME, YFCLOUD_REPO_VERSION);
    }
}
